//
//  PictureSelectorViewController.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/26.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import SnapKit

private let pictureSelectCellId = "pictureSelectCell"
//每行图片数
private let coloumCount:CGFloat = 3
//最大图片数
private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    //图片数组
    lazy var imageList = [UIImage]()
    //构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        let w = (KWidth - (coloumCount + 1) * pictureMargin) / coloumCount
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureMargin
        layout.minimumLineSpacing = pictureMargin
        //设置组间距
        layout.sectionInset = UIEdgeInsets(top: pictureMargin, left: pictureMargin, bottom: 0, right: pictureMargin)
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.backgroundColor = UIColor.whiteColor()
        // Register cell classes
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: pictureSelectCellId)
        
    }
    
}
extension PictureSelectorViewController: PictureSelectCellDelegate{
    func userWillDeletePicture(cell:PictureSelectCell) {
        print(__FUNCTION__)
        if let indexPath = collectionView?.indexPathForCell(cell) {
            self.imageList.removeAtIndex(indexPath.item)
        }
        collectionView?.reloadData()
    }
    func userWillChosePicture() {
        print(__FUNCTION__)
        //图片选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
}
extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}
extension PictureSelectorViewController {
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //通过操作数据达到选择图片到一定数目不能选择的功能
        let detil = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + detil
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureSelectCellId, forIndexPath: indexPath) as! PictureSelectCell
        cell.backgroundColor = UIColor.randomColor()
        cell.pictureSelectCellDelegate = self
        if imageList.count == indexPath.item {
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}
//协议
protocol PictureSelectCellDelegate:NSObjectProtocol {
    //声明方法
    func userWillChosePicture()
    
    func userWillDeletePicture(cell:PictureSelectCell)
}


//自定义Cell
class PictureSelectCell:UICollectionViewCell {
    
    weak var pictureSelectCellDelegate:PictureSelectCellDelegate?
    //外界设置图片的属性
    var image:UIImage? {
        didSet {
            //删除按钮是否隐藏
            deleteBtn.hidden = image == nil
            //图片设置
            addBtn.setImage(image, forState: .Normal)
        }
    }
    //MARK:按钮点击事件
    @objc private func addBtnDidClick(){
        if self.image != nil {
            print("已有图")
            return
        }
        pictureSelectCellDelegate?.userWillChosePicture()
    }
    @objc private func deleteBtnDidClick(){
        pictureSelectCellDelegate?.userWillDeletePicture(self)
    }
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        addSubview(addBtn)
        addSubview(deleteBtn)

        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        //设置按钮的视图显示样式  本身知识按钮的显示样式  但是真正起作用的是按钮内部的imageView在显示图片
        addBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill

        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
        }
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    
    private lazy var addBtn:UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var deleteBtn:UIButton = UIButton(backImageName: nil, imageName: "compose_photo_close")
}

